<template>
  <h2>用户列表</h2>
  <!-- 添加按钮 -->
  <div style="text-align: left">
    <el-button type="danger" @click="openUserDialog">添加用户</el-button>

  </div>
  <!-- table组件 -->
  <el-table :data="userList" stripe style="width: 100%">
    <el-table-column prop="id" label="用户编号" width="180"/>
    <el-table-column prop="uname" label="用户名" width="180"/>
    <el-table-column prop="phone" label="电话"/>
    <el-table-column prop="edu" label="学历"/>
    <el-table-column prop="age" label="年龄"/>
    <el-table-column prop="title" label="部门"/>
    <el-table-column fixed="right" label="操作" width="120">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="deleteUser(scope.row.id)">删除</el-button>
        <el-button link type="primary" size="small" @click="subUpdateUser(scope.row)">修改</el-button>
      </template>
    </el-table-column>

  </el-table>
  <hr/>
  <!-- page分页组件 -->
  <el-pagination
      small
      background
      :page-size="3"
      :pager-count="10"
      layout="prev, pager, next"
      :total="total"
      class="mt-4" @current-change="handlerPageChange"/>
  <!-- 添加用户信息对话框 -->
  <el-dialog
      v-model="dialogUserVisible"
      width="80%"
  >
    <h2>添加用户信息</h2>

    <!-- 对话框中添加form -->
    <el-form :model="userForm" :rules="rules" ref="formRef" label-width="120px">
      <el-form-item label="用户名"  prop="uname" >
        <el-input v-model="userForm.uname" style="width: 80%"/>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="userForm.phone"  style="width: 80%"/>
      </el-form-item>
      <el-form-item label="学历" prop="edu">
        <el-input v-model="userForm.edu"  style="width: 80%"/>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model="userForm.age"  style="width: 80%"/>
      </el-form-item>
      <el-form-item label="部门" prop="title">
        <el-input v-model="userForm.title"  style="width: 80%"/>
      </el-form-item>

      <el-form-item label="角色" prop="rids">
        <el-select v-model="userForm.rids"
                   placeholder="请选择部门...."
                   style="width: 80%"
                   multiple>
          <el-option v-for=" opt in optRoles" :label="opt.rname"
                     :value="opt.id"
                     :key="opt.id"/>

        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="subUpdateCustForm">保存</el-button>
        <el-button @click="dialogUserVisible=false">取消</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>

</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import { request } from '../utils/request'
import {ElMessage} from "element-plus";

const formRef = ref(null);
//声明user列表集合数据
const userList=ref([]);
//声明总记录数
const total=ref(0);

const rules = {
  uname: [
    { required: true, message: '请输入管理员名称', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' }
  ],
  edu: [
    { required: true, message: '请输入学历', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年纪', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入部门', trigger: 'blur' }
  ],
  rids: [
    { required: true, message: '请输入角色', trigger: 'blur' }
  ]
};




//定义函数发送请求加载用户列表
function queryUserList(pageNum){
  request({ url: `http://localhost:8081/userList?pageNum=${pageNum}`, method: 'get' })
      .then((response)=>{
        userList.value=response.data.userList;
        total.value=response.data.total;
      })
      .catch((error)=>{
        console.log(error);
      })
}
//加载调用函数
onMounted(function(){
  queryUserList(1);
});
//定义分页按钮回调函数
function handlerPageChange(pageNum){
  //调用分页查询函数
  queryUserList(pageNum);
}
/////////////////////////////添加用户信息/////////////////////////////////
//定义添加用户信息对话框状态
const dialogUserVisible=ref(false);
//声明表单数据
const userForm=reactive({
  uname:'',
  phone:'',
  age:'',
  edu:'',
  title:'',
  rids:[]
});
//声明角色的集合
const optRoles=ref([]);
function openUserDialog(){
  dialogUserVisible.value=true;
  //发送ajax请求加载所有角色信息
  request({ url: 'http://localhost:8081/loadAllRoles', method: 'get' })
      .then((response)=>{
        optRoles.value=response.data;
      })
      .catch((error)=>{
        console.log(error);
    });
}

// 添加保存用户信息的方法
function subUpdateCustForm(){
  formRef.value.validate((valid) => {
    if (!valid) return;
    request({
      url: 'http://localhost:8081/updateUser', 
      method: 'post',
      data: userForm
    })
        .then((response)=>{
          if(response.data.code==200){
            ElMessage(response.data.msg);
            dialogUserVisible.value=false;
            // 清空表单
            userForm.uname = '';
            userForm.phone = '';
            userForm.age = '';
            userForm.edu = '';
            userForm.title = '';
            userForm.rids = [];
            // 刷新列表
            queryUserList(1);
          }else{
            ElMessage(response.data.msg);
          }
        })
        .catch((error)=>{
          console.log(error);
        });
  });
}

//删除管理员
const isDeleting=ref(false);
function deleteUser(id){
  if (isDeleting.value) return;
  isDeleting.value = true;
  request({ url: `http://localhost:8081/delUser?id=${id}`, method: 'get' })
      .then((response) => {
        if (response.data.code == 200) {
          ElMessage(response.data.msg);
          queryUserList(1)
        } else {
          ElMessage(response.data.msg);
        }
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        isDeleting.value = false;
      });
}

// 修改用户信息
function subUpdateUser(row) {
  // 回显数据到表单
  userForm.uname = row.uname;
  userForm.phone = row.phone;
  userForm.age = row.age;
  userForm.edu = row.edu;
  userForm.title = row.title;
  userForm.rids = Array.isArray(row.rids) ? row.rids : (row.rids ? row.rids.split(',') : []);
  userForm.id = row.id; // 假如有id字段
  dialogUserVisible.value = true;
}

</script>

<style scoped>

</style>